package com.zhida.smartcontrol.pagehome.deviceinfo;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.jay.tools.base.BaseDialogFragment;
import com.jay.tools.ui.ButtonStyle;
import com.jay.tools.ui.TopBarView;
import com.jay.tools.utils.EventBusUtils;
import com.tan.fonticon.widget.IconTextView;
import com.zhida.smartcontrol.MainActivity;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.common.Api;
import com.zhida.smartcontrol.common.Const;
import com.zhida.smartcontrol.common.PhotoDialogFragment;
import com.zhida.smartcontrol.common.PhotoOkEvent;
import com.zhida.smartcontrol.common.bean.DeviceClassifyBean;
import com.zhida.smartcontrol.common.bean.LampBean;
import com.zhida.smartcontrol.common.mapsel.MapSelFragment;
import com.zhida.smartcontrol.dialog.addqddialog.AddQdDialogFragment;
import com.zhida.smartcontrol.dialog.classifydialog.ClassifyDialogFragment;
import com.zhida.smartcontrol.dialog.devicelistdialog.DeviceListDialogFragment;
import com.zhida.smartcontrol.dialog.grouplistdialog.GroupListDialogFragment;
import com.zhida.smartcontrol.dialog.kzqlistdialog.KzqListDialogFragment;
import com.zhida.smartcontrol.mvp.MVPBaseFragment;
import com.zhida.smartcontrol.pagectrl.ProjectListBean;
import com.zhida.smartcontrol.pagectrl.editproject.EditProjectFragment;
import com.zhida.smartcontrol.pagectrl.projectdetail.GroupBean;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;
import org.angmarch.views.SpinnerTextFormatter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author: tanjianpei
 * date: 2019/10/9 009 15:39
 * description: 设备信息
 */
public class DeviceInfoFragment extends MVPBaseFragment<DeviceInfoContract.View, DeviceInfoPresenter> implements DeviceInfoContract.View {
    @BindView(R.id.top)
    TopBarView mTopBar;
    @BindView(R.id.et_imei)
    EditText mEtImei;
    @BindView(R.id.et_code)
    EditText mEtCode;
    @BindView(R.id.tv_device_type)
    TextView mTvDeviceType;
    @BindView(R.id.et_factory)
    EditText mEtFactory;
    @BindView(R.id.et_device_name)
    EditText mEtDeviceName;
    @BindView(R.id.et_num)
    EditText mEtNum;
    @BindView(R.id.tv_project_name)
    TextView mTvProjectName;
    @BindView(R.id.btn_add_project)
    ButtonStyle mBtnAddProject;
    @BindView(R.id.icon_right)
    IconTextView mIconRight;
    @BindView(R.id.tv_qu_duan)
    TextView mTvQuduan;
    @BindView(R.id.tv_kongzhiqi)
    TextView mTvKongzhiqi;
    @BindView(R.id.ll_kongzhiqi)
    LinearLayout mLlKongzhiqi;

    @BindView(R.id.btn_add_quduan)
    ButtonStyle mBtnAddQuduan;
    @BindView(R.id.btn_add_kongzhiqi)
    ButtonStyle mBtnAddKongzhiqi;
    @BindView(R.id.icon_right_1)
    IconTextView mIconRight1;
    @BindView(R.id.et_lng)
    EditText mEtLng;
    @BindView(R.id.et_lat)
    EditText mEtLat;
    @BindView(R.id.et_iccid)
    EditText et_iccid;
    @BindView(R.id.et_address)
    EditText mEtAddress;
    @BindView(R.id.iv_code)
    ImageView mIvCode;
    @BindView(R.id.tv_code)
    TextView mTvCode;
    @BindView(R.id.ll_anzhuangxinxi)
    LinearLayout ll_anzhuangxinxi;
    @BindView(R.id.sp_huganqipeibi)
    NiceSpinner sp_huganqipeibi;
    @BindView(R.id.sp_suoshuxiangmu)
    NiceSpinner sp_suoshuxiangmu;
    @BindView(R.id.view_huganqi)
    View view_huganqi;
    @BindView(R.id.ll_huganqi)
    LinearLayout ll_huganqi;

    private DeviceClassifyBean mClassifyBean;
    private ProjectListBean mProjectBean;
    private GroupBean mGroupBean;
    private LampBean mLampBean;

    private DeviceBean mBean;
    private String mLat, mLng;
    private String mFilePath;

    private String mPicUrl;
    private boolean mLoadOk;
    private boolean isAdd = true;
    List<String> bianjiemaData = new ArrayList<>();
    private int bianjiema = 0;
    List<String> huganqiData = new ArrayList<>();
    private String huganqi = "";


    public static DeviceInfoFragment newInstance(String result) {
        Bundle args = new Bundle();
        args.putString("result", result);
        DeviceInfoFragment fragment = new DeviceInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected Object getLayout() {
        return R.layout.fragment_device_info;
    }

    @Override
    protected void initLazy(Bundle savedInstanceState) {
        inflateTopBar(mTopBar);
        String result = getArguments().getString("result");
        if (null != result && !result.isEmpty()) {
            if (result.contains("{") && result.contains("}")) {
                isAdd = false;
                try {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    mPresenter.findByQrCode(jsonObject.getString("imei"), "");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ll_anzhuangxinxi.setVisibility(View.VISIBLE);
            } else {
                isAdd = true;
                String[] split;
                if (result.contains(",")) {
                    split = result.split(",");
                } else {
                    split = result.split(";");
                }
                mPresenter.findByQrCode(split[0], split[1]);
                ll_anzhuangxinxi.setVisibility(View.GONE);
                mEtImei.setEnabled(TextUtils.isEmpty(split[0]));

                mEtImei.setText(split[0]);
                mEtCode.setText(split[1]);
            }
        }
        bianjiemaData.add("旧编解码插件");
        bianjiemaData.add("新编解码插件");
        bianjiema = 0;
        SpinnerTextFormatter textFormatter = (SpinnerTextFormatter<String>) SpannableString::new;

        sp_suoshuxiangmu.setSpinnerTextFormatter(textFormatter);
        sp_suoshuxiangmu.setSelectedTextFormatter(textFormatter);
        sp_suoshuxiangmu.setOnSpinnerItemSelectedListener((parent, view, position, id) -> bianjiema = position);
        sp_suoshuxiangmu.attachDataSource(bianjiemaData);

        huganqiData.add("30:5");
        huganqiData.add("50:5");
        huganqiData.add("75:5");
        huganqiData.add("100:5");
        huganqiData.add("150:5");
        huganqiData.add("200:5");
        huganqiData.add("250:5");
        huganqiData.add("300:5");
        huganqi = huganqiData.get(0);
        sp_huganqipeibi.setSpinnerTextFormatter(textFormatter);
        sp_huganqipeibi.setSelectedTextFormatter(textFormatter);
        sp_huganqipeibi.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                huganqi = huganqiData.get(position);
            }
        });
        sp_huganqipeibi.attachDataSource(huganqiData);

        EventBusUtils.register(this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }

    @OnClick({R.id.ll_project, R.id.btn_add_project, R.id.btn_add_quduan, R.id.tv_device_type,
            R.id.ll_quduan, R.id.ll_kongzhiqi, R.id.btn_add_kongzhiqi, R.id.ll_jwd, R.id.btn_add, R.id.iv_code, R.id.tv_code})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_device_type:
                showDialog(ClassifyDialogFragment.newInstance(), 0);
                break;
            case R.id.ll_project:
                showDialog(DeviceListDialogFragment.newInstance(), 1);
                break;
            case R.id.btn_add_project:
                start(EditProjectFragment.newInstance("", Const.TYPE_ADD));
                break;
            case R.id.ll_quduan:
                if (null == mProjectBean || TextUtils.isEmpty(mProjectBean.getId())) {
                    showMsg("请选择项目");
                    return;
                }
                showDialog(GroupListDialogFragment.newInstance(mProjectBean.getId()), 2);
                break;
            case R.id.btn_add_quduan:
                if (null == mProjectBean || TextUtils.isEmpty(mProjectBean.getId())) {
                    showMsg("请选择项目");
                    return;
                }
                AddQdDialogFragment.newInstance("", mProjectBean.getId(), "").showDialog(getChildFragmentManager());
                break;
            case R.id.ll_kongzhiqi:
                if (null == mProjectBean || TextUtils.isEmpty(mProjectBean.getId())) {
                    showMsg("请选择项目");
                    return;
                }
                if (null == mGroupBean || TextUtils.isEmpty(mGroupBean.getId())) {
                    showMsg("请选择区段");
                    return;
                }
                showDialog(KzqListDialogFragment.newInstance(mGroupBean.getId()), 3);
                break;
            case R.id.ll_jwd:
                startForResult(MapSelFragment.newInstance(), 0);
                break;
            case R.id.btn_add:
                String factory = mEtFactory.getText().toString().trim();
                String imei = mEtImei.getText().toString().trim();
                String eCode = mEtCode.getText().toString().trim();
                String name = mEtDeviceName.getText().toString().trim();
                String num = mEtNum.getText().toString().trim();
                String iccid = et_iccid.getText().toString().trim();

                String address = mEtAddress.getText().toString().trim();
                String gId = "";
                if (mBean != null) {
                    gId = mBean.getId();
                }
                String projectBeanId = "";
                if (mProjectBean != null) {
                    projectBeanId = mProjectBean.getId();
                }
                String groupBeanId = "";
                if (mGroupBean != null) {
                    groupBeanId = mGroupBean.getId();
                }
                String lampBeanId = "";
                if (mLampBean != null) {
                    lampBeanId = mLampBean.getId();
                }
//                if (mClassifyBean.getName().contains("灯")) {
//                    if (null != mGroupBean) {
//                        gId = mGroupBean.getId();
//                    }
//                } else {
//                    if (null != mLampBean) {
//                        gId = mLampBean.getId();
//                    }
//                }
                mPresenter.check(mClassifyBean, address, mLat, mLng, eCode, num, name, imei,
                        factory, gId, mBean, mFilePath, bianjiema, huganqi, iccid, lampBeanId, groupBeanId, projectBeanId);


                break;
            case R.id.iv_code:
                if (mLoadOk) {

                } else {
                    loadPic();
                }
                break;
            case R.id.tv_code:
                requestCameraPermission();
                break;
        }
    }

    @Override
    protected void openCamera() {
        PhotoDialogFragment.newInstance().showDialog(getChildFragmentManager());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void photoOk(PhotoOkEvent event) {
        mFilePath = event.getPath();
        Glide.with(getProxyActivity())
                .load(mFilePath)
                .apply(new RequestOptions()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE))
                .into(mIvCode);
        mLoadOk = true;
    }

    private void showDialog(BaseDialogFragment fragment, int type) {
        fragment.setOnDestroyListener(new BaseDialogFragment.OnDestroyListener() {
            @Override
            public void onDestroy(Object object, boolean isChange) {
                if (null == object) {
                    return;
                }
                switch (type) {
                    case 0:
                        mClassifyBean = (DeviceClassifyBean) object;
                        mTvDeviceType.setText(mClassifyBean.getName());
                        if (mClassifyBean.getName().contains("灯")) {
                            mLlKongzhiqi.setVisibility(View.VISIBLE);
                            view_huganqi.setVisibility(View.GONE);
                            ll_huganqi.setVisibility(View.GONE);
                        } else {
                            mLlKongzhiqi.setVisibility(View.GONE);
                            view_huganqi.setVisibility(View.VISIBLE);
                            ll_huganqi.setVisibility(View.VISIBLE);
                        }
                        break;
                    case 1:
                        mProjectBean = (ProjectListBean) object;
                        mTvProjectName.setText(mProjectBean.getProjectName());
                        break;
                    case 2:
                        mGroupBean = (GroupBean) object;
                        mTvQuduan.setText(mGroupBean.getName());
                        break;
                    case 3:
                        mLampBean = (LampBean) object;
                        mTvKongzhiqi.setText(mLampBean.getName());
                        break;
                }
            }
        });
        fragment.showDialog(getChildFragmentManager());
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 0 && null != data) {
            mLat = data.getString("lat");
            mLng = data.getString("lng");
            mEtLat.setText(mLat);
            mEtLng.setText(mLng);
        }
    }

    @Override
    public void showBean(DeviceBean bean) {
        mBean = bean;
        et_iccid.setText(bean.getIccid());
        huganqi = bean.getTransformerRatio();
        for (int i = 0; i < huganqiData.size(); i++) {
            if (huganqiData.get(i).equals(huganqi)) {
                sp_huganqipeibi.setSelectedIndex(i);
            }
        }
        bianjiema = Integer.parseInt(bean.getPluginVersion());
        sp_huganqipeibi.setSelectedIndex(bianjiema);

        mEtImei.setEnabled(TextUtils.isEmpty(bean.getImei()));

        mEtImei.setText(bean.getImei());
        mEtCode.setText(bean.getEquipmentCode());

        mClassifyBean = new DeviceClassifyBean(bean.getSwitchType(), bean.getSwitchTypeTxt());
        if (mClassifyBean.getName().contains("灯")) {
            mLlKongzhiqi.setVisibility(View.VISIBLE);
            view_huganqi.setVisibility(View.GONE);
            ll_huganqi.setVisibility(View.GONE);
        } else {
            mLlKongzhiqi.setVisibility(View.GONE);
            view_huganqi.setVisibility(View.VISIBLE);
            ll_huganqi.setVisibility(View.VISIBLE);
        }
        mTvDeviceType.setText(mClassifyBean.getName());

        mEtFactory.setText(bean.getManufacturer());
        mEtDeviceName.setText(bean.getName());
        mEtNum.setText(bean.getNum() + "");
        mIconRight.setVisibility(View.GONE);

        mIconRight1.setVisibility(View.GONE);
        mEtLng.setText(bean.getLng());
        mEtLat.setText(bean.getLat());
        mEtAddress.setText(bean.getAddress());
        mTvCode.setText("设备二维码");

        mBtnAddProject.setNormalBackgroundColor(0xff3862FF);
        mBtnAddProject.setPressedBackgroundColor(0xff3862FF);
        mBtnAddProject.setNormalTextColor(Color.WHITE);
        mBtnAddProject.setPressedTextColor(Color.WHITE);

        mBtnAddQuduan.setNormalBackgroundColor(0xff3862FF);
        mBtnAddQuduan.setPressedBackgroundColor(0xff3862FF);
        mBtnAddQuduan.setNormalTextColor(Color.WHITE);
        mBtnAddQuduan.setPressedTextColor(Color.WHITE);

        mBtnAddKongzhiqi.setNormalBackgroundColor(0xff3862FF);
        mBtnAddKongzhiqi.setPressedBackgroundColor(0xff3862FF);
        mBtnAddKongzhiqi.setNormalTextColor(Color.WHITE);
        mBtnAddKongzhiqi.setPressedTextColor(Color.WHITE);
        mLat=bean.getLat();
        mLng=bean.getLng();
        mPicUrl = bean.getDevicePic();
        loadPic();
        if (!bean.getProjectBaseId().isEmpty()){
            mPresenter.requestProject(bean.getProjectBaseId());
        }
        if (!bean.getGroupId().isEmpty()){
            mPresenter.requestGroup(bean.getProjectBaseId(),bean.getGroupId());
        }
        if (!bean.getPid().isEmpty()){
            mPresenter.requestKzq(bean.getGroupId(),bean.getPid());
        }
    }

    private void loadPic() {
        if (!TextUtils.isEmpty(mPicUrl))
            Glide.with(getProxyActivity())
                    .load(Api.PIC + mPicUrl)
                    .apply(new RequestOptions()
                            .placeholder(R.drawable.progress_round)
                            .error(R.drawable.ic_photo))
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            mLoadOk = false;
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            mLoadOk = true;
                            return false;
                        }
                    })
                    .into(mIvCode);
    }

    @Override
    public void unInstallDevice(String imei, String code) {
        mBean = null;
        mEtImei.setEnabled(TextUtils.isEmpty(imei));
        mEtCode.setEnabled(TextUtils.isEmpty(code));
        mEtImei.setText(imei);
        mEtCode.setText(code);

        mTvCode.setHint("请拍摄二维码图片");
        mBtnAddProject.setNormalBackgroundColor(0xfffafafa);
        mBtnAddProject.setPressedBackgroundColor(0xfffafafa);
        mBtnAddProject.setNormalTextColor(0xff999999);
        mBtnAddProject.setPressedTextColor(0xff999999);

        mBtnAddQuduan.setNormalBackgroundColor(0xfffafafa);
        mBtnAddQuduan.setPressedBackgroundColor(0xfffafafa);
        mBtnAddQuduan.setNormalTextColor(0xff999999);
        mBtnAddQuduan.setPressedTextColor(0xff999999);
    }

    @Override
    public void showGroup(GroupBean groupBean) {
        mGroupBean =  groupBean;
        mTvQuduan.setText(mGroupBean.getName());
    }

    @Override
    public void showProject(ProjectListBean projectListBean) {
        mProjectBean = projectListBean;
        mTvProjectName.setText(mProjectBean.getProjectName());
    }

    @Override
    public void showKzq(LampBean lampBean) {
        mLampBean = lampBean;
        mTvKongzhiqi.setText(mLampBean.getName());
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        stateBar(true);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        stateBar(false);
    }

}
